#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>

#define BUFFER_SIZE 64

int main()
{
    /* 创建管道 */
    int pipeFd[2] = {0};
    int ret = pipe(pipeFd);
    if(ret == -1)
    {
        perror("create pipe error\n");
        _exit(-1);
    }


    /* 创建子进程 */
    pid_t pid = fork();
    if(pid < 0)
    {
        perror("fork error\n");
        _exit(-1);
    }
    else if(pid == 0)
    {
        /* 把写关闭 */
        close(pipeFd[1]);
        /* 子进程 */
        /* 子进程负责读 */

        sleep(10);
        char buf[BUFFER_SIZE] = {0};
        /* read是一个阻塞函数 */
        int readBytes = read(pipeFd[0],buf,sizeof(buf));
        printf("child readBytes = %d,\tbuf = %s\n",readBytes,buf);
    }
    else
    {
        /* 把读关闭 */
        close(pipeFd[0]);
        int cnt = 0;
        /* 父进程 */
        /* 父进程负责写 */
        while(1)
        {
            sleep(1);

            char buffer[512] ;
            memset(buffer,'s',sizeof(buffer));
            /* 向管道里写数据 */
            write(pipeFd[1],(const void *)buffer,strlen(buffer));
        }
#if 0
        char buf[BUFFER_SIZE] = {0};
        
        int readBytes = read(pipeFd[0],buf,strlen(buffer));
        printf("parent readBytes = %d,\tbuf = %s\n",readBytes,buf);
#endif
        /* 阻塞回收等待子进程 */
        wait(NULL);
        printf("recycle success\n");

    }


    return 0;
}
